package tptecnicas.printers.parser;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import tptecnicas.logging.MessageInfo;

/**
 * Clase encargada de analizar y resolver el codigo 
 * asociado a la fecha, en el formato de log.
 */
public class DateReplacer implements FormatReplacer {

	private Pattern patternToMatch;
	private Matcher matcher;

	/**
	 * Constructor
	 * 
	 * @param token: format identifier to replace
	 */
	public DateReplacer() {
		patternToMatch = null;
	}

	@Override
	public String toString() {
		return "datetime";
	}
	
	@Override
	public String replace(MessageInfo info, String formatLine) {
		
		String aux;
		this.patternToMatch = Pattern.compile("%d" + Pattern.quote("{") + "([^}]*)" + Pattern.quote("}"));
		matcher = patternToMatch.matcher(formatLine);
		if (matcher.find()) {
			try {
				SimpleDateFormat date = new SimpleDateFormat(matcher.group(1));
				aux = matcher.replaceAll(date.format(new Date()));
			} catch (Exception e) {
				return formatLine;
			}
			return aux;
		}
		return formatLine;
	}

	@Override
	public String getValue(MessageInfo info) {
		SimpleDateFormat date = new SimpleDateFormat();
		return date.format(new Date());
	}
}